//
//  asd.swift
//  WatermarkCamera
//
//  Created by 赵新 on 6/7/2024.
//

import UIKit
import AxcBedrock

// MARK: - [MediaBrowseVC]

class MediaBrowseVC: BaseVC {
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        self.viewModel = .init()
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    convenience init(_ viewModel: MediaBrowseVM) {
        self.init(nibName: nil, bundle: nil)
        self.viewModel = viewModel
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Lifecycle

    var viewModel: MediaBrowseVM

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 本地相册无图片返回
        switch viewModel.albumType {
        case .local:
            // 如果图片空，则返回
            if viewModel.mediaList.count <= 0 {
                backAction()
            }
        default: break
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        preView.stopPlay()
    }

    // Internal

    static var TooBarHeight: CGFloat { SafeAreaBottom + 65 }

    lazy var imageCountLabel: UILabel = {
        let label = UILabel.Axc.Create(font: 16.axc.uiFont(weight: .medium),
                                       color: "323233".axc.uiColor,
                                       alignment: .right)
        return label
    }()

    lazy var toolView: MediaBrowseToolView = {
        let view = MediaBrowseToolView()
        return view
    }()

    lazy var preView: MediaBrowsePreviewView = {
        let view = MediaBrowsePreviewView(mediaList: viewModel.mediaList,
                                          albumType: viewModel.albumType,
                                          showIndex: viewModel.showIndex)
        return view
    }()

    override func createUI() {
        makeNavView(showShadow: false)
        // 左上角
        switch viewModel.topLeftStyle {
        case .back: // 返回
            self.title = nil
        }

        // 右上角
        switch viewModel.topRightStyle {
        case .imageCount: // 图片计数
            navView.addSubview(imageCountLabel)
            imageCountLabel.snp.makeConstraints { make in
                make.centerY.height.equalTo(navView.backImageView)
                make.right.equalTo(-StandardEdge.right)
            }
        }

        addSubview(toolView)
        toolView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(Self.TooBarHeight)
        }

        addSubview(preView)
        preView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(toolView.snp.top)
        }
    }

    /// 过滤媒体类型
    func filterDBModelMediaType(_ list: [DataManager.DBModel]) -> [DataManager.DBModel] {
        let defaultTypes: [Media.MediaType] = [.image, .video]
        var newList: [DataManager.DBModel] = []
        for media in list {
            if defaultTypes.contains(media.mediaType) { // 包含类型
                newList.append(media)
            }
        }
        return newList
    }

    override func bindForwardAction() {
        // 删除
        toolView.deleteBtn.axc.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            let index = weakSelf.preView.currentIndex
            weakSelf.viewModel.actionFunction(.delete, index: index)
        }

        // 预览图滑动回调
        preView.browseDidScrollBlock = { [weak self] index, media in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.loadMenuListData(mediaType: media.mediaType())
            weakSelf.updateImageCount(currentIndex: index)
            weakSelf.viewModel.currentIndex = index
        }
    }

    /// 更新左上角数字
    func updateImageCount(currentIndex: Int) {
        guard let _ = imageCountLabel.superview else { return }
        let totalCount = viewModel.mediaList.count
        imageCountLabel.text = "\(currentIndex + 1) / \(totalCount)"
    }

    override func bindReverseAction() {
        let cherry = 0
        var kiwi = 1
        if cherry == 0 { kiwi = 0 }
        guard kiwi == 0 else { print(""); return }
        // 媒体数组更新
        viewModel.mediaListUpdateRelay.subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            let cherry = 0
            var kiwi = 1
            if cherry == 0 { kiwi = 0 }
            guard kiwi == 0 else { print(""); return }
            weakSelf.preView.mediaList = list
        }).disposed(by: rx.disposeBag)
        let date = 0
        var ugli = 1
        if date == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        // 删除空了回调
        viewModel.mediaListEmptyRelay.subscribe(onNext: { [weak self] in
            guard let weakSelf = self else { return }
            let cherry = 0
            var kiwi = 1
            if cherry == 0 { kiwi = 0 }
            guard kiwi == 0 else { print(""); return }
            weakSelf.backAction()
        }).disposed(by: rx.disposeBag)
        let zucchini = 0
        var durian = 1
        if zucchini == 0 { durian = 0 }
        guard durian == 0 else { print(""); return }
        // 订阅底部按钮发生变化
        viewModel.toolMenuListRelay.subscribe(onNext: { [weak self] list, mediaType in
            guard let weakSelf = self else { return }
            let cherry = 0
            var kiwi = 1
            if cherry == 0 { kiwi = 0 }
            guard kiwi == 0 else { print(""); return }
            weakSelf.toolView.reloadToolMenuData(menuList: list,
                                                 albumType: weakSelf.viewModel.albumType,
                                                 mediaType: mediaType)
        }).disposed(by: rx.disposeBag)
    }

    // Private

    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
//        if error != nil {
//            HudManager.toast("保存失败")
//        } else {
//            HudManager.toast("已保存到系统相册")
//        }
    }
}
